package com.cc.data_explore.gui.tab;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cc.data_explore.logic.mybatis.DbHelper;
import com.cc.data_explore.logic.mybatis.mapper.main.BaseDbMapper;
import com.cc.data_explore.logic.mybatis.model.BaseDb;
import de.saxsys.mvvmfx.MvvmFX;
import de.saxsys.mvvmfx.ViewModel;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.hutool.core.text.StrUtil;

import java.util.List;

/**
 * WorkspaceView
 *
 * @author aa
 * @version 1.0
 * @since 2025/4/2
 */
public class WorkspaceViewModel implements ViewModel {

    private final ObservableList<BaseDb> dbs = FXCollections.observableArrayList();
    private final StringProperty searchText = new SimpleStringProperty();

    public void initialize() {
        loadBaseDb();
    }

    public void loadBaseDb() {
        dbs.clear();
        SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory(DbHelper.MAIN_DB_NAME);
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            BaseDbMapper mapper = session.getMapper(BaseDbMapper.class);
            List<BaseDb> baseDbs = mapper.selectList(Wrappers.<BaseDb>lambdaQuery()
                    .like(StrUtil.isNotEmpty(getSearchText()), BaseDb::getDbName, getSearchText()));
            dbs.addAll(baseDbs);
        }
    }

    public ObservableList<BaseDb> dbs() {
        return dbs;
    }

    public void delBaseDb(BaseDb baseDb) {
        SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory(DbHelper.MAIN_DB_NAME);
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            BaseDbMapper mapper = session.getMapper(BaseDbMapper.class);
            mapper.delete(Wrappers.<BaseDb>lambdaQuery().eq(BaseDb::getId, baseDb.getId()));
            loadBaseDb();
            MvvmFX.getNotificationCenter().publish("MAIN_VIEW_DEL_TAB", baseDb.getDbFile());
        }
    }

    public String getSearchText() {
        return searchText.get();
    }

    public StringProperty searchTextProperty() {
        return searchText;
    }
}
